var rpio = require('rpio');

let Trig_pin = 29;     // 定义 排针的第40引脚接 模块的发射引脚
let Echo_pin = 28;     // 定义 排针的第38引脚接模块的接收引脚

// 引脚初始化
function systemInit(){
    rpio.open(Trig_pin, rpio.OUTPUT,rpio.LOW); 
    rpio.open(Echo_pin, rpio.INPUT, rpio.PULL_DOWN); 
    rpio.sleep(10);
}
// 获取测量的距离
function getDis(){
    let start = 0;
    let stop = 0;
    rpio.write(Trig_pin, rpio.LOW);
    rpio.msleep(100);
    rpio.write(Trig_pin, rpio.HIGH);
    rpio.usleep(20);

    while((rpio.read(Echo_pin) == rpio.HIGH));
    start = (new Date()).getTime();
    console.log('start = ' + start);

    while(!(rpio.read(Echo_pin) == rpio.LOW));
    stop = (new Date()).getTime();
    console.log('stop = ' + stop);

    var dis = (stop - start)*34/2
    console.log('data = ' + (stop - start));
    console.log('dis = ' + dis + 'cm');
}

function main() {
    systemInit();
    while(1){
        getDis();
        rpio.sleep(5);
    }
}
main();
